import React, { useEffect, useState } from "react";
import { Button, Space, Row, Col, List, Modal, message, Input, } from "antd";
import { PlusOutlined } from '@ant-design/icons';
import { ProColumnType, ProTable } from "@ant-design/pro-components";
import { dictTypeTypes, dictValueTypes  } from "@/constants/types";
import { fetchListDictType, fetchListDictTypeValue } from "../services";
import TypeCreateModal from "../modals/TypeCreateModal";
import TypeValueCreateModal from "../modals/TypeValueCreateModal";
import { addDictType, addDictValue, deleteDictValue, updateDictValue } from "../services";
import { modalPropsType } from '@/constants/types';
import { useRequest } from "ahooks";
import { useModel } from "@umijs/max";
import {useComponentDidMount} from '@/hooks'
import './index.less';


const DictTypeList = ({value, onChange, onRefresh}: {value: dictTypeTypes | null; onChange: Function, onRefresh: Function}) => {
  const [dictTypes, setDictTypes] = useState<dictTypeTypes []>([]);
  const [searchTypes, setSearchDictTypes] = useState<dictTypeTypes []>([]);
  const {loading: addDictTypeLoading, runAsync: addDictTypeApi} = useRequest(addDictType, {manual: true});
  const [visible, setVisible] = useState<boolean>(false);


  // 获取字典类型
  const getTypesApi = async () => {
    try {
      const res = await fetchListDictType();
      setDictTypes([...(res || [])]);
      setSearchDictTypes([...(res || [])]);
      if (res?.length > 0) {
        onChange(res[0])
      }
    } catch(err) {
      console.log('err', err);
    }
  }

  // 字典类型
  const typeCreateProps: modalPropsType = {
    visible,
    loading: addDictTypeLoading,
    onSubmit: async (params: dictTypeTypes) => {
      const res = await addDictTypeApi(params);
      if (res.code === '0') {
        setVisible(false);
        getTypesApi();
        onRefresh();
      }
    },
    onCancel:() => {
      setVisible(false);
    }
  }
  const handleTypeAdd = () => {
    setVisible(true);
  }

  const handleSearch = (e: { currentTarget: { value: string; }; }) => {
    const txt = e.currentTarget.value.trim();
      if (!txt) {
        setSearchDictTypes([...dictTypes]);
        return;
      }
      setSearchDictTypes([...dictTypes.filter((v: dictTypeTypes) => v.dictName?.indexOf(txt) >= 0)]);
  }
  
  useComponentDidMount(() => {
    getTypesApi();
  })
  return (
    <>
      <Col span={4} className="list-wrapper">
        <Space direction="horizontal">
          <Input
            onChange={handleSearch}           
            allowClear
            placeholder="回车搜索"
          />
          <Button onClick={handleTypeAdd} type="primary" icon={<PlusOutlined />} />
        </Space>
        <List
          className="demo-loadmore-list list-content"
          itemLayout="horizontal"
          dataSource={searchTypes}
          renderItem={(item) => (
            <List.Item
              onClick={() => onChange(item)} 
              className={item.dictType === value?.dictType ? 'list-item checked' : 'list-item'} 
              key={item.dictType}>
              {item.dictName}
            </List.Item>
          )}  
        />
      </Col>
      {visible && <TypeCreateModal {...typeCreateProps} />}
    </>
  );
}

const DictTypeValueTable = ({type, onRefresh}: {type: dictTypeTypes | null, onRefresh: any}) => {
  const [dictValues, setDictValues] = useState<dictValueTypes []>([]);
  const [typeValueVisible, setTypeValueVisible] = useState<boolean>(false);
  const [typeValueRow, setTypeValueRow] = useState<dictValueTypes | null>(null);
  const {loading: addDictValueLoading, runAsync: addDictValueApi} = useRequest(addDictValue, {manual: true});
  const {loading: updateDictValueLoading, runAsync: updateDictValueApi} = useRequest(updateDictValue, {manual: true});

  // 根据字典类型获取字典值
  const getValuesApi = async () => {
    const res = await fetchListDictTypeValue({dictType: type?.dictType});
    setDictValues(res || []);
  }

  // 字典类型值
  const typeValueCreateProps: modalPropsType = {
    typeRow: type,
    loading: addDictValueLoading || updateDictValueLoading,
    visible: typeValueVisible,
    currentRow: typeValueRow,
    onSubmit: async (params: dictValueTypes) => {
      const apiFunc = typeValueRow ? updateDictValueApi : addDictValueApi;
      const res = await apiFunc(typeValueRow ? {
        ...params, 
        id: typeValueRow?.id
      } : params);
      if (res.code === '0') {
        message.success('操作成功');
        setTypeValueVisible(false);
        setTypeValueRow(null);
        getValuesApi();
        onRefresh();
      }
    },
    onCancel:() => {
      setTypeValueVisible(false);
      setTypeValueRow(null);
    }
  }

  const handleTypeValueAdd = () => {
    setTypeValueVisible(true);
  }
  const handleTypeValueEdit = (record: dictValueTypes) => {
    setTypeValueVisible(true);
    setTypeValueRow(record);
  }
  const handleTypeValueDel = (record: dictValueTypes) => {
    Modal.confirm({
      title: '温馨提示',
      content: '是否确定删除？',
      onOk: () => {
        deleteDictValue({id: record.id}).then(res => {
          setTypeValueVisible(false);
          setTypeValueRow(null);
          getValuesApi();
        })
      }
    });
  }

  const columns: ProColumnType<dictValueTypes > [] = [
    {
      title: '字典词',
      search: false,
      dataIndex: 'dictLabel',
    },
    {
      title: '词代码',
      search: false,
      dataIndex: 'dictValue',
    },
    {
      title: '类型',
      dataIndex: 'dictType'
    },
    {
      title: '操作',
      dataIndex: 'options',
      search: false,
      render: (_, record: dictValueTypes) => {
        return (
          <Space>
            <Button type="link" onClick={() => handleTypeValueEdit(record)}>编辑</Button>
            <Button type="link" onClick={() => handleTypeValueDel(record)}>删除</Button>
          </Space>
        );
      }
    }
  ];

  useEffect(() => {
    if (type?.dictType) {
      getValuesApi();
    }
  }, [type?.dictType]);


  return (
    <>
      <Col span={20}>
        <ProTable
          className="xl-no-search-protable"
          rowKey="dictValue"
          bordered
          search={false}
          options={false}
          columns={columns}
          dataSource={dictValues}
          toolBarRender={() => [
            <Button onClick={handleTypeValueAdd} type="primary">
              <PlusOutlined />
              新建值
            </Button>,
          ]}
        />
      </Col>
      {typeValueVisible && <TypeValueCreateModal {...typeValueCreateProps} />}
    </>
  );

}

const DataDict = () => {
  const { refreshDict } = useModel('dictModel');
  const [currentType, setCurrentType] = useState<dictTypeTypes | null>(null);

  const dictTypeProps = {
    value: currentType,
    onChange: (type: dictTypeTypes) => {
      setCurrentType(type);
    },
    onRefresh: () => {
      refreshDict();
    }
  }

  const dictTypeValueProps = {
    type: currentType,
    onRefresh: () => {
      refreshDict();
    }
  }
  return (
    <> 
      <Row gutter={20} style={{backgroundColor: '#fff'}}>
        <DictTypeList {...dictTypeProps} />
        <DictTypeValueTable {...dictTypeValueProps} />
      </Row>
    </>
  );
};


export default DataDict;